const express = require('express');  
const multer = require('multer');  
const {guid} = require('../utils/index')
const path = require('path');  
const fs = require('fs')
const router = express.Router();
const uploadDir = './uploads'; // 设置上传文件存放的根目录  
  
// 自定义存储引擎  
const storage = multer.diskStorage({  
  destination: function (req, file, cb) {  
    // 获取当前日期并格式化  
    const date = new Date();  
    const year = date.getFullYear();  
    const month = String(date.getMonth() + 1).padStart(2, '0');  
    const day = String(date.getDate()).padStart(2, '0');  
  
    // 创建年月日文件夹  
    const dirPath = path.join(uploadDir, `${year}/${month}/${day}`);  
    if (!fs.existsSync(dirPath)) {  
      fs.mkdirSync(dirPath, { recursive: true });  
    }  
  
    cb(null, dirPath);  
  },  
  filename: function (req, file, cb) {  
    // 生成随机ID  
    // const randomId = cryptoRandomString({ length: 10, type: 'alphanumeric' });  
    const randomId = guid()
    // 设置文件名  
    const fileName = `${randomId}-${file.originalname}`;  
    cb(null, fileName);  
  }  
});  
  
// 设置上传限制和存储引擎  
const upload = multer({  
  storage: storage,  
  limits: { fileSize: 10 * 1024 * 1024 }, // 设置文件大小为10MB  
  fileFilter: function (req, file, cb) {  
    // 只允许上传图片文件  
    const fileTypes = /jpeg|jpg|png|gif/;  
    const mimeType = fileTypes.test(file.mimetype);  
  
    // 使用自定义过滤器  
    if (mimeType) {  
      return cb(null, true);  
    }  
    cb('Error: Images only! Please upload an image');  
  }  
});  
  
router.post('/upload', upload.single('file'), (req, res) => {  
  // 文件信息可以从req.file获取  
  if (!req.file) {  
    return res.status(400).send('No file uploaded.');  
  }  
  
  // 构造完整的文件路径  
  const filePath = path.join(req.file.destination, req.file.filename);  
  
  // 返回文件路径信息  
  res.json({  
    originalname: req.file.originalname,  
    filename: req.file.filename,  
    destination: req.file.destination,  
    path: filePath  
  });  
});  

// 导出路由
module.exports = router;